<template>
  <view class="add-address">
    <div class="uForm">
      <u-form :border-bottom="false" :model="form" ref="uForm" :error-type="['toast']" :rule="rules">
        <u-form-item class="border" label="收货人" label-width="130" prop="name">
          <u-input v-model="form.name" clearable placeholder="请输入收货人姓名" />
        </u-form-item>

        <u-form-item label="手机号码" label-width="130" prop="mobile">
          <u-input v-model="form.mobile" type="number" maxlength="11" placeholder="请输入收货人手机号码" />
        </u-form-item>

        <u-form-item label="地址" label-width="130" prop="address">
          <div @click="goToAddressSearch" class="address-input">
            {{ form.address || '请输入地址' }}
          </div>
        </u-form-item>

        <u-form-item label="Unit#" label-width="130" prop="unit">
          <u-input v-model="form.detail" placeholder="请输入单元号" />
        </u-form-item>

        <u-form-item label="邮编" label-width="130" prop="addressNo">
          <u-input v-model="form.addressNo" placeholder="邮编将自动填充" readonly />
        </u-form-item>
        <u-checkbox-group shape="circle" size="30">
          <u-checkbox :active-color="lightColor" v-model="form.isDefault">设为默认地址</u-checkbox>
        </u-checkbox-group>

        <div class="saveBtn" @click="submit">保存</div>
      </u-form>


    </div>
  </view>
</template>
<script>
import { addAddress, editAddress, getAddressDetail } from "@/api/address.js";
export default {
  components: {},
  onShow() {
    // 判断当前系统权限定位是否开启
    // 处理从地址搜索页面返回的数据
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    if (currentPage.options && currentPage.options.selectedAddress) {
      // 如果有选中的地址数据，则填充表单
      const addressData = JSON.parse(decodeURIComponent(currentPage.options.selectedAddress));
      this.form.address = addressData.address;
      this.form.addressNo = addressData.addressNo || addressData.postalCode;
      this.form.country = addressData.country || "";
      this.form.province = addressData.province || "";
      this.form.city = addressData.city || "";
      this.form.addressCity = addressData.addressCity || addressData.city || "";
      this.form.addressProvince = addressData.addressProvince || addressData.province || "";
      this.form.addressCountry = addressData.addressCountry || addressData.country || "";
    }

    // 监听地址选择事件
    uni.$on('address_selected', this.handleAddressSelected);
  },

  onHide() {
    // 移除事件监听
    uni.$off('address_selected', this.handleAddressSelected);
  },
  methods: {
    // 处理地址选择事件
    handleAddressSelected(addressData) {
      this.form.address = addressData.address;
      this.form.addressNo = addressData.addressNo;
      this.form.country = addressData.country || "";
      this.form.province = addressData.province || "";
      this.form.city = addressData.city || "";
      this.form.addressCity = addressData.addressCity || "";
      this.form.addressProvince = addressData.addressProvince || "";
      this.form.addressCountry = addressData.addressCountry || "";
    },

    // 跳转到地址搜索页面
    goToAddressSearch() {
      console.log('goToAddressSearch');

      uni.navigateTo({
        url: '/pages/mine/address/search'
      });
    },

    // 提交
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.form.consigneeAddressPath = this.form.address
          this.form.consigneeAddressIdPath = ','
          let submitData = JSON.parse(JSON.stringify(this.form));
          if (this.routerVal == "edit") {
            submitData.id = this.id;
            editAddress(submitData).then((res) => {
              if (res.success) {
                uni.showToast({
                  title: "修改成功",
                  icon: "none",
                });
                uni.navigateBack();
              }
            });
          } else {
            addAddress(submitData).then((res) => {
              if (res.success) {
                uni.showToast({
                  title: "添加成功",
                  icon: "none",
                });
                uni.navigateBack();
              }
            });
          }
        }
      });
    },


  },
  mounted() { },
  data() {
    return {
      lightColor: this.$lightColor, //高亮颜色
      routerVal: "",
      form: {
        name: "", //收货人姓名
        mobile: "", //收货人手机
        address: "", //地址
        detail: "", //Unit#
        addressNo: "", //邮编
        alias: "", //地址别名
        isDefault: false, //是否为默认地址
        country: "", //国家
        province: "", //省份
        city: "", //城市
        addressCity: "", //地址城市
        addressProvince: "", //地址省份
        addressCountry: "", //地址国家
      },
      rules: {
        name: {
          rules: [
            {
              required: true,
              errorMessage: "收货人不能为空",
            },
          ],
        },
        mobile: {
          rules: [
            {
              required: true,
              errorMessage: "手机号不能为空",
            },
          ],
        },
        address: {
          rules: [
            {
              required: true,
              errorMessage: "地址不能为空",
            },
          ],
        },
      },
      id: "", //地址id
    };
  },
  onLoad(option) {
    uni.showLoading({
      title: "加载中",
    });
    this.routerVal = option;
    // 如果当前是编辑地址,则需要查询出地址详情信息
    if (option.id) {
      this.id = option.id;
      getAddressDetail(option.id).then((res) => {
        console.log('编辑地址详情返回数据:', res);
        if (res.data.success) {
          console.log('地址详情数据:', res.data.result);
          // 确保所有字段都正确赋值
          this.form = {
            ...this.form,
            ...res.data.result
          };
          this.form.address = this.form.consigneeAddressPath
          console.log('表单数据已更新:', this.form);
        } else {
          uni.showToast({
            title: res.message || '获取地址详情失败',
            icon: 'none'
          });
        }
        if (this.$store.state.isShowToast) { uni.hideLoading() };
      }).catch((error) => {
        console.error('获取地址详情失败:', error);
        uni.showToast({
          title: '获取地址详情失败',
          icon: 'none'
        });
        if (this.$store.state.isShowToast) { uni.hideLoading() };
      });
    } else {
      uni.hideLoading();
    }
  },
  // 初始化rules必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>
<style scoped lang="scss">
.detailAddress {
  /deep/ .u-form-item--left {
    display: flex;
    align-items: flex-start;
  }
}

.saveBtn,
.selectAddress {
  height: 70rpx;

  line-height: 70rpx;
  text-align: center;
  font-size: 30rpx;
  background: $aider-light-color;
  color: #fff;
  width: 70%;
  margin: 40rpx auto 0 auto;
  border-radius: 20rpx;
}

.selectAddress {
  margin-top: 40rpx;
  background: #fff;

  color: $aider-light-color;
  border: 2rpx solid $aider-light-color;
}

.uForm {
  width: 94%;
  overflow: hidden;
  left: 3%;
  position: relative;
  top: 2%;
  background: #fff;
  border-radius: 20rpx;
  padding: 0 0 40rpx 0;
}

.add-address {
  width: 100%;
  padding-top: 3%;

  /deep/ .u-form-item {
    background-color: #fff;
    padding: 24rpx 30rpx;
  }

  .u-btn {
    margin: 30rpx 30rpx 0 30rpx;
    background-color: $main-color;
  }

  /deep/.u-checkbox {
    margin: 30rpx 30rpx 0 30rpx;

    .u-label-class.u-checkbox__label {
      color: $font-color-light;
      font-size: $font-sm;
    }
  }
}

/deep/ .u-checkbox__label {
  font-size: 28rpx;
}

.address-input {
  padding: 20rpx 0;
  color: #333;
  font-size: 28rpx;
  border-bottom: 1px solid #eee;
  min-height: 40rpx;
  display: flex;
  align-items: center;
}

.address-input:empty::before {
  content: '请输入地址';
  color: #999;
}
</style>
